package com.kly.cashmall.framework.manager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import androidx.annotation.NonNull;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import java.util.HashSet;

public class IBroadcastManager {

  private static IBroadcastManager sInstance;

  private LocalBroadcastManager broadcastManager;

  private HashSet<String> actionSet;

  private IBroadcastManager(Context context) {
    this.broadcastManager = LocalBroadcastManager.getInstance(context);
    actionSet = new HashSet<>();
  }

  public static IBroadcastManager getInstance(Context context) {
    if (sInstance == null) {
      sInstance = new IBroadcastManager(context);
    }
    return sInstance;
  }

  public boolean sendBroadcast(Intent intent) {
    if (actionSet.contains(intent.getAction())) {
      broadcastManager.sendBroadcast(intent);
      return true;
    } else {
      return false;
    }
  }

  public void registerReceiver(BroadcastReceiver receiver, @NonNull IntentFilter filter) {
    broadcastManager.registerReceiver(receiver, filter);
    for (int i = 0; i < filter.countActions(); i++) {
      String action = filter.getAction(i);
      actionSet.add(action);
    }
  }

  public void unregisterReceiver(BroadcastReceiver receiver) {
    broadcastManager.unregisterReceiver(receiver);
  }
}
